//
//  USUploadPhotoController.m
//  us
//
//  Created by karry on 2025/4/14.
//

#import "USUploadPhotoController.h"

#import <QuickLookThumbnailing/QuickLookThumbnailing.h>
#import "USAlertTipBar.h"
#import "USUploadPhotoCell.h"
#import "USDateAlertView.h"
#import "USMediaUploadManager.h"
#import "USMediaPickerManager.h"
#import "USPhotoUploadTool.h"
@interface USUploadPhotoController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, assign) NSInteger type;
@property (nonatomic, strong) UIButton *uploadBtn;
@property (nonatomic,strong) UIBarButtonItem *addItem;

@property (nonatomic,strong) USShareSpaceModel *spaceModel;

@end

@implementation USUploadPhotoController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"准备上传";
    [self setupView];
    
    [self getShareSpace];
}

- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    
    self.us_tableView.contentInset = UIEdgeInsetsMake(40 + 12, 0, UIButton.us_buttonDefaultHeight + 12 + self.view.safeAreaInsets.bottom + 12, 0);
    
}

- (void)setupView{
    
    self.addItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_add"] style:UIBarButtonItemStylePlain target:self action:@selector(addAction:)];
    self.navigationItem.rightBarButtonItem = self.addItem;
    
    RACSignal *imageArraySignal = [RACObserve(self, mediaList) map:^id _Nullable(NSArray *arr) {
        [self.uploadBtn setTitle:[NSString stringWithFormat:@"上传 （%ld张）",self.mediaList.count] forState:0];
        return @(arr.count < 20);
    }];

    RACSignal *enableSignal = [RACSignal combineLatest:@[imageArraySignal]
                                                 reduce:^id(NSNumber *hasImage){
        return @([hasImage boolValue]);
    }];

    RAC(self.navigationItem.rightBarButtonItem, enabled) = enableSignal;
    
    
    self.us_tableView.emptyDataSetSource = nil;
    self.us_tableView.emptyDataSetDelegate = self;
    self.us_tableView.delegate = self;
    self.us_tableView.dataSource = self;
    [self.us_tableView registerNib:[UINib nibWithNibName:@"USUploadPhotoCell" bundle:nil] forCellReuseIdentifier:@"USUploadPhotoCellId"];

    USAlertTipBar *tipBar = [[USAlertTipBar alloc]initWithFrame:CGRectZero];
    tipBar.style = USAlertTipBarStyleDefault;
    tipBar.color = UIColor.us_redColor;
    tipBar.titleLab.text = @"在相册中，将按拍摄时间排序";
    tipBar.titleLab.font = [UIFont systemFontOfSize:15];
    
    [self.view addSubview:tipBar];
    [tipBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.height.mas_equalTo(40);
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
    }];
    
    UIButton *uploadBtn = [UIButton us_fillButtonWithTitle:[NSString stringWithFormat:@"上传 （%ld张）",self.mediaList.count]];
    [uploadBtn addTarget:self action:@selector(uploadAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:uploadBtn];
    self.uploadBtn = uploadBtn;
    
    [uploadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.height.mas_equalTo([UIButton us_buttonDefaultHeight]);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-12);
    }];
    
    UISegmentedControl *seg = [[UISegmentedControl alloc]initWithItems:@[@"统一为今天",@"使用照片时间"]];
    seg.selectedSegmentTintColor = [UIColor mi_1_color];
    seg.selectedSegmentIndex = 0;
    [self.view addSubview:seg];
    [seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    [seg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-20);
        make.bottom.mas_equalTo(uploadBtn.mas_top).mas_offset(-12);
    }];
    
    UILabel *label = [UILabel new];
    label.text = @"上传时间";
    label.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.centerY.mas_equalTo(seg);
    }];
    
    [self.us_tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop).mas_offset(0);
        make.left.right.mas_offset(0);
        make.bottom.mas_equalTo(seg.mas_top).mas_offset(-12);
    }];

}
- (NSMutableArray <USMediaResult *>*)mediaList {
    if (_mediaList == nil) {
        _mediaList = [NSMutableArray array];
    }
    return _mediaList;
}
- (void)startUpload{
    [self.indicator startAnimating];
    UIBarButtonItem *loadingItem = [[UIBarButtonItem alloc] initWithCustomView:self.indicator];
    self.navigationItem.rightBarButtonItem = loadingItem;
    self.view.userInteractionEnabled = NO;
    
}
- (void)endUpLoad{
    self.navigationItem.rightBarButtonItem = self.addItem;
    [self.indicator stopAnimating];
    self.view.userInteractionEnabled = YES;
}

- (void)getShareSpace{

    [[EMNetWork shareManager] em_post:API_SharedSpaceInfo
                               params:@{}
                                  hud:nil
                            showError:YES
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            return;
        }
 
        self.spaceModel = [USShareSpaceModel mj_objectWithKeyValues:api.data[@"sharedSpace"]];
        
 
    } fail:^{
        
        
    }];
    
    
}
- (void)addAction:(UIBarButtonItem *)sender{

    @weakify(self)
    DTItem *item0 = [DTItem itemWithTitle:@"拍摄" image:[UIImage imageNamed:@"icon-camera-22"] tag:0 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self takePhotoAction];
    }];
    
    DTItem *item1 = [DTItem itemWithTitle:@"相册" image:[UIImage imageNamed:@"icon-photo-22"] tag:0 identifier:nil handle:^(DTItem *item) {
        @strongify(self)
        [self presentImagePicker];
    }];

    DTTargetView *view = [DTTargetView initWithBarItem:sender item:@[item0,item1]];
    
    [view show];
    
}
- (void)takePhotoAction{
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        picker.videoMaximumDuration = 60;
        picker.allowsEditing = NO; // 是否允许编辑
        picker.showsCameraControls = YES;
        picker.mediaTypes = @[UTTypeImage.identifier, UTTypeMovie.identifier];
        [self presentViewController:picker animated:YES completion:nil];
    } else {
        [self.view us_makeAlert:@"当前设备不支持拍照" subTitle:nil];
    }
    
}
- (void)presentImagePicker{
    [USFeedbackTool impactSoft];
    [self startUpload];

    @weakify(self)
    [USMediaPickerManager presentPickerFrom:self type:USPickerMediaType_Image_Video limit:20 - self.mediaList.count didFinishPicking:^{

    } progressHandler:^(NSInteger current, NSInteger total) {
   
        @strongify(self)
        
        NSLog(@"%ld",current);
        
    } completion:^(NSArray<USMediaResult *> * _Nonnull results) {
        @strongify(self)
        [self endUpLoad];
        
        
        for (USMediaResult *media in results) {
            if (self.type == 0) {
                media.customDate = (NSInteger)[[NSDate date] timeIntervalSince1970];
            }else {
                media.customDate = media.recordDate;
            }
        }
        
        NSMutableArray *newArray = [self.mediaList mutableCopy];
        [newArray addObjectsFromArray:results];
        self.mediaList = newArray;
        
        [self.us_tableView reloadData];
    }];
    
}
#pragma mark - UIImagePickerControllerDelegate,UINavigationControllerDelegate;

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {

    NSString *mediaType = info[UIImagePickerControllerMediaType];

    if ([mediaType isEqualToString:UTTypeImage.identifier]) {
        // 图片
        UIImage *image = info[UIImagePickerControllerOriginalImage];
        NSData *imageData = UIImageJPEGRepresentation(image, 1);
        NSString *tmpPath = [USPhotoUploadTool imagePathWithUUID:NSUUID.UUID.UUIDString];
        [imageData writeToFile:tmpPath atomically:YES];
        
        
        USMediaResult *item = [[USMediaResult alloc] init];
        item.uuid = [[NSUUID UUID] UUIDString];
        item.filePath = tmpPath;
        item.type = USMediaTypeImage;
        item.recordDate = (NSInteger)[[NSDate date] timeIntervalSince1970];
        item.customDate = (NSInteger)[[NSDate date] timeIntervalSince1970];
        
        
        NSMutableArray *newArray = [self.mediaList mutableCopy];
        [newArray addObject:item];
        self.mediaList = newArray;
        
        [self.us_tableView reloadData];

    } else if ([mediaType isEqualToString:UTTypeMovie.identifier]) {
        
        // 视频
        NSURL *videoURL = info[UIImagePickerControllerMediaURL];
        NSString *path = [USPhotoUploadTool videoPathWithUUID:NSUUID.UUID.UUIDString];
        NSURL *tmpURL = [NSURL fileURLWithPath:path];
        NSError *error = nil;
        [[NSFileManager defaultManager] copyItemAtURL:videoURL toURL:tmpURL error:&error];
        if (error) {
            [self.view makeToast:error.localizedDescription];
            return;
        }
        
        USMediaResult *item = [[USMediaResult alloc] init];
        item.uuid = [[NSUUID UUID] UUIDString];
        item.filePath = path;
        item.type = USMediaTypeVideo;
        item.recordDate = (NSInteger)[[NSDate date] timeIntervalSince1970];
        item.customDate = (NSInteger)[[NSDate date] timeIntervalSince1970];
        
       
        NSMutableArray *newArray = [self.mediaList mutableCopy];
        [newArray addObject:item];
        self.mediaList = newArray;
        
        
        [self.us_tableView reloadData];

    }

    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)segAction:(UISegmentedControl *)sender{
    self.type = sender.selectedSegmentIndex;
    [USFeedbackTool selectionChanged];
}

- (void)setType:(NSInteger)type{
    _type = type;
 
    NSArray<NSIndexPath *> *visibleIndexPaths = [self.us_tableView indexPathsForVisibleRows];
    for (NSIndexPath *indexPath in visibleIndexPaths) {
        USUploadPhotoCell *cell = [self.us_tableView cellForRowAtIndexPath:indexPath];
        if (cell) {
            USMediaResult *result = self.mediaList[indexPath.row];
            if (type == 0) {
                result.customDate = (NSInteger)[[NSDate date] timeIntervalSince1970];
            }else {
                result.customDate = result.recordDate;
            }
            cell.dateLab.text = [[NSDate dateWithTimeIntervalSince1970:result.customDate] jk_formatYMD];

        }
    }

}

- (void)uploadAction:(id)sender{
    
    
    if (self.spaceModel.albumStorageSize >= 500) {
        
        MOAlertBaseView *alert = [[MOAlertBaseView alloc]initWithTitle:@"相册存储空间已达上限\n塞不进去啦~" detailTitle:nil contentView:nil leftButtonImageName:@" " rightButtonImageName:nil autoDissmiss:YES tapDissmiss:YES];
        
        [alert show];
        return;
    }
     
    self.view.userInteractionEnabled = NO; // 禁用整个页面操作

    [USFeedbackTool impactMedium];
    
    self.uploadBtn.enabled = NO;
    
    [EMHudManager show:@"上传中..."];
 
    [USMediaUploadManager uploadImages:self.mediaList albumFirstDirectory:self.albumFirstDirectory albumSecondDirectory:self.albumSecondDirectory progress:^(NSInteger current, NSInteger total) {

        dispatch_async(dispatch_get_main_queue(), ^{
            if (total == 1) {
                // 单个文件上传进度
                [EMHudManager showProgress: current / 100.0];
                [EMHudManager show:[NSString stringWithFormat:@"上传中 %li%%", current]];
             } else {
                // 多个文件上传进度
                 [EMHudManager showProgress: (float)current / (float)total];
                 [EMHudManager show:[NSString stringWithFormat:@"上传中 %ld/%ld", (long)current, (long)total]];
            }
        });
    } success:^(NSArray<USPhotoModel *> *models) {
        
        [self uploadPhotos:models];
    } failure:^(NSError *error) {
        
    }];
}

- (void)uploadPhotos:(NSArray <USPhotoModel *>*)photos{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"albumId"] = self.albumId;

    NSMutableArray *list = [NSMutableArray array];
    for (USPhotoModel *model in photos) {
        [list addObject:@{
            @"cosUrl":model.cosUrl?:@"",
            @"type":@(model.type),
            @"photoFirstDirectory" :model.photoFirstDirectory?:@"",
            @"photoSecondDirectory":model.photoSecondDirectory?:@"",
            @"recordDate": @(model.recordDate),
            @"fileName":model.fileName?:@"",
            @"liveMovUrl":model.liveMovUrl?:@"",
            @"liveMoveFileName":model.liveMoveFileName?:@"",
            @"size":@(model.size),
            @"liveMovSize":@(model.liveMovSize)
        }];
    }

    params[@"photoList"] = list;

    @weakify(self)
    [[EMNetWork shareManager] em_post:API_AlbumAddPhotos
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {
        @strongify(self)
        if (api.success) {
            if (self.uploadSuccessPhotos) {
                NSArray *photoList = [USPhotoModel mj_objectArrayWithKeyValuesArray:api.data[@"photoList"]];

                self.uploadSuccessPhotos(photoList);
                
                [self remindAction];
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    } fail:^{
        
    }];
}

#pragma mark - 提醒Ta
- (void)remindAction {
    
    NSString *action_title = [NSString stringWithFormat:@"%@更新了相册内容",USUser.user.nickname];
    NSDictionary *ext = @{@"action_id":self.albumId,
                          @"action_title":action_title,
                          @"action_content":@"点击查看"};
    [USIMCmdCustomManager imSendCmdWithAction:USIMCmdAction_Photo andExt:ext];

    [USIMCmdCustomManager imSendCustomWithEvent:USIMCmdAction_Photo andCustomExt:ext];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:@(USNoticeType_Photo) forKey:@"type"];
    [param setValue:self.albumId forKey:@"pkId"];
    [param setValue:@"更新了相册内容" forKey:@"content"];
    [param setValue:USUser.user.relUser.userId forKey:@"userId"];
    [param setValue:@(1) forKey:@"shareSpaceFlag"];
    [[EMNetWork shareManager] em_post:NoticeAdd
                               params:param
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
 
    } fail:^{
        
        
    }];
}

//更改时间
- (void)prepareSetDateAction:(NSIndexPath *)indexPath{
    USMediaResult *media = self.mediaList[indexPath.row];
    
    USDateAlertView *alert = [[USDateAlertView alloc]initWithDate:[NSDate date] andSubTitle:@"设置日期" limitToNow:YES];
    [alert showInView:UIViewController.topViewController.view];
    @weakify(self)
    alert.didChooseBlock = ^(NSDate * _Nonnull date) {
        @strongify(self)
       
        media.customDate = (NSInteger)[date timeIntervalSince1970];
        USUploadPhotoCell *cell = [self.us_tableView cellForRowAtIndexPath:indexPath];
        if (cell) {
            NSDate *date = [NSDate dateWithTimeIntervalSince1970:media.customDate];
            cell.dateLab.text = [date jk_formatYMD];
        }
        
    };
 
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.mediaList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    USUploadPhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"USUploadPhotoCellId"];
    
    @weakify(self);
    cell.editDateBlock = ^{
        @strongify(self);
        [self prepareSetDateAction:indexPath];
    };
 

    USMediaResult *result = self.mediaList[indexPath.row];

    cell.videoImageView.hidden = result.type == USMediaTypeVideo ? NO : YES;
    if (self.type == 0) {
        cell.dateLab.text = [[NSDate date] jk_formatYMD];
    }else {
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:result.customDate];
        cell.dateLab.text = [date jk_formatYMD];
    }

    NSURL *url = [NSURL fileURLWithPath:result.filePath?:@""];

    if (url) {
        if (result.type == USMediaTypeLivePhoto) {
            cell.imageV.image = [UIImage imageWithContentsOfFile:result.filePath];
        }else {
            QLThumbnailGenerationRequest *request = [[QLThumbnailGenerationRequest alloc]initWithFileAtURL:url size:CGSizeMake(200, 200) scale:UIScreen.mainScreen.scale representationTypes:QLThumbnailGenerationRequestRepresentationTypeThumbnail];
            
            [[QLThumbnailGenerator sharedGenerator]generateBestRepresentationForRequest:request completionHandler:^(QLThumbnailRepresentation * _Nullable thumbnail, NSError * _Nullable error) {
               
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (error) {
                        cell.imageV.image = [UIImage us_placeHolderImage];
                        return;
                    }
                    cell.imageV.image = thumbnail.UIImage;
                });
                
            }];
        }
    }
 

    return cell;
    
}
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView
trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive
                                                                                title:@"删除"
                                                                              handler:^(UIContextualAction *action, UIView *sourceView, void (^completionHandler)(BOOL)) {
        // 1. 更新数据
 
        NSMutableArray *newArray = [self.mediaList mutableCopy];
        [newArray removeObjectAtIndex:indexPath.row];
        self.mediaList = newArray;
        
        
        // 2. 删除cell
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
     }];
    
    UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[deleteAction]];
    return config;
}





@end
